package com.cfpamf.ms.insur.pay.config;

import com.cfpamf.common.ms.mybatis.CommonXMLMapperBuilder;
import com.cfpamf.common.ms.mybatis.KeyGenMode;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import javax.sql.DataSource;

/**
 * Create By zhengjing on 2019/4/17 16:19
 */
@Configuration
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class DataBaseConfiguration {

    @Autowired
    private MybatisProperties properties;

    private ResourceLoader resourceLoader = new DefaultResourceLoader();

    @Value("${mybatis.keyGenMode:IDENTITY}")
    private String keyGenMode;


    /**
     * 注入SqlSessionFactory
     *
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        CommonXMLMapperBuilder builder = new CommonXMLMapperBuilder();
        builder.setBaseResultMap("BaseResultMap");
        builder.setBaseTableName("BaseTable");
        builder.setGenerationType("GenerationType");
        builder.setBaseColumns("BaseColumn");
        builder.setKeyGenMode(KeyGenMode.parse(StringUtils.defaultString(keyGenMode, KeyGenMode.IDENTITY.getCode())));
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(dataSource);
        if (this.properties.getConfigLocation() != null) {
            factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
        }
        factory.setConfiguration(properties.getConfiguration());
        factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
        factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());

        Resource[] all = this.properties.resolveMapperLocations();
        Resource[] resources = builder.builderCommonMapper(this.properties.resolveMapperLocations());

        //修复公用报丢弃的内容
        for (int i = 0; i < resources.length; i++) {
            if (resources[i] == null) {
                resources[i] = all[i];
            }
        }
        factory.setMapperLocations(resources);
        return factory.getObject();

    }
}
